//
//  AppDelegate.m
//  Logistics
//
//  Created by 华谕 on 2017/10/30.
//  Copyright © 2017年 HUYU. All rights reserved.
//

#import "AppDelegate.h"
#import <QMapKit/QMapKit.h>
#import <QMapSearchKit/QMapSearchKit.h>
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>

@interface AppDelegate ()<WXApiDelegate>
@property (nonatomic, strong)NSString *code;
@property (nonatomic, strong)NSString *updateurl;
@property (nonatomic, strong) CTCallCenter *center;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
//    [LTools storage:NO ForKey:SERVER_IsLogin];
    [WXApi registerApp:@"wx8248d3b78d0454bb"];
    [QMapServices sharedServices].APIKey = TenxunMapKey;
    [[QMSSearchServices sharedServices] setApiKey:TenxunMapKey];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    if ([LTools storageForKey:SERVER_IsLogin])
    {
        if ([[LTools cacheForKey:SERVER_LoginData] isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *obj = [LTools cacheForKey:SERVER_LoginData];
            if (obj.allKeys.count > 0)
            {
                UserAccountModel *model = [UserAccountModel shareMange];
                [model jsonUserData:obj];
                NSLog(@"model----%@",model.username);
                
            }
            
        }
    }
    
    self.tabbarViewController = [[HYTabBarViewController alloc] init];
    self.window.rootViewController = _tabbarViewController;
    [self callPhone];
    return YES;
}


- (void)callPhone
{
    WEAKSELF;
    _center = [[CTCallCenter alloc] init];
    _center.callEventHandler = ^(CTCall* call) {
        if ([call.callState isEqualToString:CTCallStateDisconnected])
        {
            NSLog(@"挂断了电话咯Call has been disconnected");
        }
        else if ([call.callState isEqualToString:CTCallStateConnected])
        {
            NSLog(@"电话通了Call has just been connected");
        }
        else if([call.callState isEqualToString:CTCallStateIncoming])
        {
            NSLog(@"来电话了Call is incoming");
            
        }
        else if ([call.callState isEqualToString:CTCallStateDialing])
        {
            NSLog(@"正在播出电话call is dialing");
            NSString *time = [weakSelf getCurrentTimes];
            NSNotification * notice = [NSNotification notificationWithName:@"callPhones" object:time];
            
            [[NSNotificationCenter defaultCenter] postNotification:notice];
        }
        else
        {
            NSLog(@"嘛都没做Nothing is done");
        }
    };
}

- (void)getapp_Version
{
    //获取版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    //版本号信息存到NSUserDefaults沙盒
    [LTools cache:app_Version ForKey:kAppVersion];
    //如果有更新的版本，提醒用户下载
    [self getUpdateInformation];
    
}

- (void)getUpdateInformation
{
    [LTools versionForAppid:@"1309472776" Block:^(BOOL isNewVersion, NSString *updateUrl, NSString *updateContent)
     {
         if (isNewVersion==YES)
         {
             self.updateurl = updateUrl;
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"专线网提醒您有新版本" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
             alert.tag = 1015;
             [alert show];
         }
     }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1015)
    {
        if(buttonIndex==1)
        {
            NSURL *url = [NSURL URLWithString:self.updateurl];
            [[UIApplication sharedApplication]openURL:url];
        }
        
    }
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    
    [WXApi handleOpenURL:url delegate:self];
    
    return YES;
}

// 微信 授权后回调
- (void)onResp:(BaseResp *)resp{
    
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *temp = (SendAuthResp *)resp;
        if ([self.code isEqualToString:temp.code])
        {
            return;
        }
        self.code = temp.code;
        if (temp.code != nil)
        {
            [self weixinLogin:self.code];
        }
        
    }
    
    if ([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        if (resp.errCode == 0)
        {
            //成功
            [self requestAddShareCount];
        }
        else
        {
            
        }
    }
    if ([resp isKindOfClass:[PayResp class]])
    {
        PayResp *response = (PayResp *)resp;
        switch (response.errCode)
        {
            case WXSuccess:
            {
                [LTools showMBProgressWithText:@"付款成功" addToView:self.window];
                NSNotification * notice = [NSNotification notificationWithName:@"PaySuccess" object:nil];
                //                发送消息
                [[NSNotificationCenter defaultCenter] postNotification:notice];
                break;
            }
                
            default:
            {
                //                [LTools showMBProgressWithText:@"付款失败" addToView:self.window];
                break;
            }
        }
    }
    
    
    
    
}

- (void)requestAddShareCount
{
    [HYBaseHandler requestWithTheFormUrl:SERVER_addShareCount Parmers:nil Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            
        }
        else
        {
            
        }
        
    } failed:^(NSError *error) {
        
    }];
}

- (void)weixinLogin:(NSString *)code
{
//    WEAKSELF;
    NSDictionary *dic = @{@"code":code};
    [HYBaseHandler requestWithTheFormUrl:SERVER_weChatAppLogin Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            NSString *token = obj[@"data"][@"token"];
            [LTools storage:YES ForKey:SERVER_IsLogin];
            [LTools cache:token ForKey:SERVER_LoginToken];
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:0];
            [dictionary addEntriesFromDictionary:obj];
            NSDictionary *reloadDic = [NSDictionary changeType:dictionary];
            [LTools cache:reloadDic ForKey:SERVER_LoginData];
            UserAccountModel *model = [UserAccountModel shareMange];
            [model jsonUserData:reloadDic];
            NSNotification * notice = [NSNotification notificationWithName:@"bangdingsuccess" object:nil];
            //                发送消息
            [[NSNotificationCenter defaultCenter] postNotification:notice];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:self.window];
        }
        
    } failed:^(NSError *error) {
        
    }];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    if ([WXApi handleOpenURL:url delegate:self]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([WXApi handleOpenURL:url delegate:self]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    return YES;
}

//获取当前的时间
- (NSString *)getCurrentTimes
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY/MM/dd HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
